﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.WebUI.Models.SystemUser;
using XRM.Security.WebUI.Models.WorkKind;
using db = XRM.Security.DataAccess.Models;

namespace XRM.Security.WebUI.Models.Request
{
    public class RequestSearchModel
    {
        [Display(Name = "Поиск")]
        public string TextFilter { get; set; }
        [Display(Name = "Искать среди недействующих")]
        public bool ShowAllFilter { get; set; }

        public List<RequestSearchItem> RequestList { get; set; }
    }

    public class RequestModel : BaseViewModel, IValidatableObject
    {
        public RequestModel()
        {
            WorkKindList = new List<RequestWorkKindModel>();
			Status = RequestStatus.InWork;
        }

        public RequestModel(db.Request dbEntity)
        {
            WorkKindList = new List<RequestWorkKindModel>();
            WorkKindIdClose = -1;
            if (dbEntity != null)
            {
                Id = dbEntity.RequestId;
                Number = dbEntity.Number;
                CreateDate = dbEntity.CreateDate;
                DeadLine = dbEntity.DeadLine;
                CancelDate = dbEntity.CloseDate;
                UserRegisterId = dbEntity.UserRegisterId;
                if (dbEntity.UserRegister != null)
                    UserRegisterName = dbEntity.UserRegister.FullName();

                SystemUserId = dbEntity.SystemUserId;
                RequestSystemUser = new SystemUserModel(dbEntity.SystemUser);

                Comment = dbEntity.Comment;

                Status = (RequestStatus)dbEntity.Status;

                if (dbEntity.RequestWorkKinds != null && dbEntity.RequestWorkKinds.Any())
                {
                    foreach (db.RequestWorkKind item in dbEntity.RequestWorkKinds)
                    {
                        WorkKindList.Add(new RequestWorkKindModel(item));
                    }
                }
            }
        }
		
		public void GetWorkKindAll(List<db.WorkKind> listAll)
        {
            WorkKindAllList = new List<WorkKindModel>();
            WorkKindAllList.Add(new WorkKindModel { Id = -1, Name = "(Выберите вид работ)" });
            if (listAll != null && listAll.Any())
            {
                if (Status == RequestStatus.InWork || Status == RequestStatus.InPart)
                {
                    listAll = listAll.Where( s => !s.IsDeleted ).ToList();
                }
                foreach (db.WorkKind item in listAll)
                {
                    WorkKindAllList.Add(new WorkKindModel(item, null));
                }
            }
        }

        public void GetSystemUserAll(List<db.SystemUser> listAll)
        {
            SystemUserAllList = new List<SelectListItem>();
            SystemUserNotDeletedList = new List<SelectListItem>();

            if (listAll != null && listAll.Any())
            {
                foreach (db.SystemUser item in listAll)
                {
                    SystemUserAllList.Add(new SelectListItem { Text = item.FullName(), Value = item.Id.ToString() });
                    if (!item.IsDeleted)
                        SystemUserNotDeletedList.Add(new SelectListItem { Text = item.FullName(), Value = item.Id.ToString() });
                }
            }

            SystemUserAllList = SystemUserAllList.OrderBy(x => x.Text).ToList();
            SystemUserNotDeletedList = SystemUserNotDeletedList.OrderBy(x => x.Text).ToList();
        }

        [Display(Name = "Номер заявки")]
        public int Number { get; set; }
        
        [Display(Name = "Дата и время создания")]
        public DateTime CreateDate { get; set; }
        [Display(Name = "Крайний срок")]
        public DateTime? DeadLine { get; set; }
        public DateTime DeadLineOld { get; set; }
        public DateTime? CancelDate { get; set; }
        //public DateTime DeadLineDate { get; set; }

        [Display(Name = "Пользователь")]
        [Required(ErrorMessage = "Поле 'Пользователь' обязательное")]
        public int? UserRegisterId { get; set; }

        [Display(Name = "Исполнитель")]
        [Required(ErrorMessage = "Поле 'Исполнитель' обязательное")]
        public int SystemUserId { get; set; }

        [Display(Name = "Примечание к заявке")]
        public string Comment { get; set; }

        [Display(Name = "Статус")]
        public RequestStatus Status { get; set; }
        public string StatusCaption
        {
            get
            {
                return Status.Description();
            }
        }
        
        [Display(Name = "Дата закрытия")]
        public DateTime? CloseDate
        {
            get
            {
                if (Status == RequestStatus.Closed)
                    return WorkKindList.Max(x => x.CloseDate);
                else
                    return null;
            }
        }

        public new bool ReadOnly
        {
            get
            {
                return (Status == RequestStatus.Closed) || (Status == RequestStatus.Error);
            }
        }

        public SystemUserModel RequestSystemUser;

        [Display(Name = "Виды работ")]
        public List<RequestWorkKindModel> WorkKindList { get; set; }

        public List<SelectListItem> SystemUserAllList { get; set; }
        public List<SelectListItem> SystemUserNotDeletedList { get; set; }
        public List<WorkKindModel> WorkKindAllList { get; set; }

        public string UserRegisterName { get; set; }
        public string UserRegisterDepartmentName { get; set; }
        public string UserRegisterDepartmentAddress { get; set; }
		public string SubmitAction { get; set; }
        public int WorkKindIdClose { get; set; } 

        public bool RedirectToUserPage
        {
            get; set;
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {

            if ( !WorkKindList.Any( s => s.WorkKindId > 0 ) )
                yield return new ValidationResult( "Необходимо добавить хотя бы один вид работ", new[] { "WorkKindList" } );
        }
    }

    public class RequestCloseModel : BaseViewModel, IValidatableObject
    {
        public int? RequestId { get; set; }
        public int? RequestWorkKindId { get; set; }

        [Required(ErrorMessage = "Поле 'Дата закрытия' обязательное")]
        public DateTime? CloseDate { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if ( CloseDate > DateTime.Today )
                yield return new ValidationResult( "Указанная дата закрытия заявки еще не наступила", new[] { "CloseDate" } );
        }
    }

    public class RequestCancelModel : BaseViewModel, IValidatableObject
    {
        public int? RequestId { get; set; }

        [Required(ErrorMessage = "Поле 'Дата отмены' обязательное")]
        public DateTime? CancelDate { get; set; }

        public IEnumerable<ValidationResult> Validate( ValidationContext validationContext )
        {
            if ( CancelDate > DateTime.Today )
                yield return new ValidationResult( "Указанная дата отмены заявки еще не наступила", new[] { "CancelDate" } );
        }
    }
}